﻿using System;
using UFIDA.U9.WSS.Proxy.Json;
using UFIDA.U9.WSS.Proxy.Json.Serialization;
using UFSoft.UBF.Cust.ClassView.MVC.Json;
using UFSoft.UBF.Cust.ClassView.MVC.Utils;
using UFSoft.UBF.Service.Base;

namespace UFSoft.UBF.Cust.ClassView.MVC.Proxy
{
    /// <summary>
    ///     Json 帮助类
    /// </summary>
    public static class ProxyJsonHelper
    {
        /// <summary>
        ///     Proxy对象转为Json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="isAutoExpandMember"></param>
        /// <param name="useDataContract"></param>
        /// <param name="maxWritingDepth"></param>
        /// <returns></returns>
        internal static string ProxyObjectToJsonString(object obj, bool useDataContract,
            bool isAutoExpandMember = false, int maxWritingDepth = 1)
        {
            if (obj == null) return string.Empty;
            IContractResolver resolver = new ProxyBaseContractResolver(useDataContract);
            JsonSerializerSettings settings = JsonHelper.GetJsonSerializerSettings(resolver);
            settings.IsAutoExpandMember = isAutoExpandMember;
            if (isAutoExpandMember)
            {
                if (maxWritingDepth <= 0)
                    maxWritingDepth = 1;
                settings.MaxExpandDepth = maxWritingDepth;
            }

            //字符串默认值为空
            settings.StringDefaultValueIsEmpty = true;
            return JsonConvert.SerializeObject(obj, Formatting.None, settings);
        }

        /// <summary>
        ///     Proxy对象执行结果转为Json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="useDataContract"></param>
        /// <returns></returns>
        internal static string ProxyResultToJsonString(object obj, bool useDataContract)
        {
            if (obj == null) return string.Empty;
            IContractResolver resolver = new ProxyBaseContractResolver(useDataContract);
            JsonSerializerSettings settings = JsonHelper.GetJsonSerializerSettings(resolver);
            return JsonConvert.SerializeObject(obj, Formatting.None, settings);
        }

        /// <summary>
        ///     Json字符串转为Proxy对象
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="useDataContract"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        internal static object ProxyObjectFromJsonString(string jsonString, Type type,
            bool useDataContract)
        {
            if (string.IsNullOrEmpty(jsonString)) return null;
            IContractResolver resolver = new ProxyBaseContractResolver(useDataContract);
            JsonSerializerSettings settings = JsonHelper.GetJsonSerializerSettings(resolver);
            return JsonConvert.DeserializeObject(jsonString, type, settings) as ProxyBase;
        }
    }
}